package com.spark.core;

import java.io.IOException;
import java.util.LinkedList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;


public class ScreenHandler implements SparkHandler{
	
	private boolean stopToken = false;
	
	private SparkTemplate template;
	private XMap current = null;
	private LinkedList<XMap> stack = new LinkedList<XMap>();
	
	public ScreenHandler(SparkTemplate template){
		this.template = template;
	}

	public void processDocument(XmlPullParser xpp) throws XmlPullParserException, IOException {
		int eventType = xpp.getEventType();
		do {
			if (eventType == XmlPullParser.START_DOCUMENT) {
				startDocument();
			} else if (eventType == XmlPullParser.START_TAG) {
				processStartElement(xpp);
			} else if (eventType == XmlPullParser.END_TAG) {
				processEndElement(xpp);
			} else if (eventType == XmlPullParser.TEXT) {
				processText(xpp);
			}
			eventType = xpp.next();
		} while (eventType != XmlPullParser.END_DOCUMENT);
	}

	public XMap getRoot() {
		return current;
	}

	public void startDocument() {
		current = null;
		stack.clear();
	}

	public void endElement() {
		if (stack.size() > 0)
			current = pop();
	}

	private XMap pop() {
		XMap node = (XMap) stack.getFirst();
		stack.removeFirst();
		return node;
	}

	private void setAttribs(XMap node, XmlPullParser xpp) {
		int count = xpp.getAttributeCount();
		for (int i = 0, l = count; i < l; i++) {
			String attrib_name = xpp.getAttributeName(i);
			node.put(attrib_name, xpp.getAttributeValue(i));
		}
	}

	private void push(XMap node) {
		stack.addFirst(node);
	}

	public void processStartElement(XmlPullParser xpp) {
		if(stopToken == true) return;
		String name = xpp.getName();
		String uri = xpp.getNamespace();
		if(SPARK_NAME_SPACE.equals(uri)){
			if(TAG_ACTIONS.equals(name)) {		
				stopToken = true;
				return;
			} else if(TAG_CACHE.equals(name) && xpp.getAttributeCount() == 1){
				String id = xpp.getAttributeValue(0);
				String str = CacheManager.getInstance().getTagHTML(template.getFilePath(), id);
				if(str!=null){
					stopToken = true;
				}
			}
		}
			
		String prefix = SPARK_NAME_SPACE.equals(uri) ? SPARK_PREFIX : "";
		XMap node = new XMap(prefix, uri, name);
		setAttribs(node, xpp);

		if (current == null) {
			current = node;
		} else {
			current.addChild(node);
			push(current);
			current = node;
		}
	}

	public void processEndElement(XmlPullParser xpp) {
		String name = xpp.getName();
		String uri = xpp.getNamespace();
		if(stopToken == true){
			if(SPARK_NAME_SPACE.equals(uri) && (TAG_ACTIONS.equals(name)||TAG_CACHE.equals(name))) {
				stopToken = false;
			} else {
				return;
			}
		}
		endElement();
	}

	public void processText(XmlPullParser xpp) throws XmlPullParserException {
		if(stopToken == true) return;
		if (current != null) {
			current.setText(xpp.getText());
		}
	}
}
